package com.pjl.restartlife.login.controller;

import cn.hutool.core.util.RandomUtil;
import com.pjl.restartlife.common.Result;
import com.pjl.restartlife.login.service.SysUserService;
import com.pjl.restartlife.login.vo.SysLoginModel;
import com.pjl.restartlife.login.vo.SysUser;
import com.pjl.restartlife.utile.AuthCodeUtil;
import com.pjl.restartlife.utile.Md5Util;
import com.pjl.restartlife.utile.RedisUtil;
import io.swagger.annotations.ApiOperation;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.UUID;

/**
 * 功能描述
 *
 * @author: jiaoli
 * @date: 2024年04月02日 21:16
 */
@RestController
@Slf4j
public class LoginControll {
    @Autowired
    SysUserService sysUserService;
    @Autowired
    RedisUtil redisUtil;

    @GetMapping("/login")
    public HashMap<String,String> loginUser(HttpServletRequest request,@RequestBody SysUser sysUser){
        log.info("用户："+sysUser.getUsername()+"=============正在登陆系统；IP地址："+request.getRemoteAddr());
        HashMap<String,String> map = new HashMap<>();
        String msg = sysUserService.login(sysUser);
        map.put("msg",msg);
        map.put("code",msg.equals("succed")?"0000":"0001");
        return map;
    }

    @GetMapping("/loginPhone")
    public HashMap<String,String> loginPhone(HttpServletRequest request,@RequestBody SysUser sysUser){
        log.info("用户："+sysUser.getUsername()+"=============正在登陆系统；IP地址："+request.getRemoteAddr());
        HashMap<String,String> map = new HashMap<>();
        String msg = sysUserService.loginPhone(sysUser);
        map.put("msg",msg);
        map.put("code",msg.equals("succed")?"0000":"0001");
        return map;
    }

    @PostMapping("/register")
    public HashMap<String,String> register(HttpServletRequest request,@RequestBody SysUser sysUser){
        HashMap<String,String> map = new HashMap<>();
        log.info("用户：=============正在注册系统；IP地址："+request.getRemoteAddr());
        sysUser.setUuid(UUID.randomUUID().toString().replaceAll("\\-",""));
        sysUser.setAddress_code(matchDistrict(sysUser.getAddree_now()));
        String msg = sysUserService.register(sysUser);
        map.put("msg",msg);
        map.put("code",msg.equals("succed")?"0000":"0001");
        return map;
    }

    /**
     * 后台生成图形验证码 ：有效
     * @param response
     * @param key
     */
    @ApiOperation("获取验证码")
    @GetMapping(value = "/randomImage/{key}")
    public Result<String> randomImage(HttpServletResponse response, @PathVariable("key") String key){
        Result<String> res = new Result<String>();
        try {
            //生成验证码
            final String BASE_CHECK_CODES = "qwertyuiplkjhgfdsazxcvbnmQWERTYUPLKJHGFDSAZXCVBNM1234567890";
            String code = RandomUtil.randomString(BASE_CHECK_CODES,4);

            //存到redis中
            String lowerCaseCode = code.toLowerCase();
            String realKey = Md5Util.md5Encode(lowerCaseCode+key, "utf-8");
            log.info("获取验证码，Redis checkCode = {}，key = {}", code, key);
            redisUtil.set(realKey, lowerCaseCode, 60);

            //返回前端
            String base64 = AuthCodeUtil.generate(code);
            res.setSuccess(true);
            res.setResult(base64);
        } catch (Exception e) {
            res.error500("获取验证码出错"+e.getMessage());
            e.printStackTrace();
        }
        return res;
    }

    @RequestMapping(value = "/checkCaptcha", method = RequestMethod.POST)
    public Result<?> checkCaptcha(@RequestBody SysLoginModel sysLoginModel){
        String captcha = sysLoginModel.getCaptcha();
        String checkKey = sysLoginModel.getCheckKey();
        if(captcha==null){
            return Result.error("验证码无效");
        }
        String lowerCaseCaptcha = captcha.toLowerCase();
        String realKey = Md5Util.md5Encode(lowerCaseCaptcha+checkKey, "utf-8");
        Object checkCode = redisUtil.get(realKey);
        if(checkCode==null || !checkCode.equals(lowerCaseCaptcha)) {
            return Result.error("验证码错误");
        }
        return Result.ok();
    }

    /**
     * 匹配地址并提取省市区(县/市)
     *
     * @param address - 完整地址
     * @return 返回配置的省市区(县 / 市)，未匹配则返回 null
     */
    public static String matchDistrict(String address) {
        if (StringUtils.isEmpty(address)) {
            return null;
        }
        // 匹配“市”字出现的次数，因为有县级市的情况，需要提取到市；否则，提取到县
        int city = address.indexOf("市");
        int sheng = address.indexOf("省");
        return address.substring(sheng + 1, city);
    }
}
